<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\library;
use GuzzleHttp\Exception\RequestException;
use think\Exception;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;

class WechatPay
{
    public $successCode = 1;
    public $failCode = 0;
    public $failMessage = '执行失败';
    public $successMessage = '执行成功';
    private $instance = null;
    private $appid = null;
    public function __construct()
    {
        $addsConfig = get_addon_config('epay');
        $merchantPrivateKeyFilePath = ROOT_PATH.$addsConfig['wechat']['cert_key'];
        $merchantPrivateKeyFile = file_get_contents($merchantPrivateKeyFilePath);
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFile, Rsa::KEY_TYPE_PRIVATE);
        $merchantCertificateSerial = '497E2865AB68FF1B506A0FD2C745909F4606A725';

        $platformCertificateFilePath = ROOT_PATH.'sql/wechatpay_4F9F00C5BC35D11CC1707EBE339119B0D56B10E1.pem';
        $platformCertificateFile = file_get_contents($platformCertificateFilePath);
        $platformPublicKeyInstance = Rsa::from($platformCertificateFile, Rsa::KEY_TYPE_PUBLIC);
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo(file_get_contents($platformCertificateFilePath));
        $this->instance = Builder::factory([
            'mchid'      => $addsConfig['wechat']['mch_id'],
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);

        $this->appid = $addsConfig['wechat']['miniapp_id'];
    }

    public function transfer($data)
    {
        $responseData = [];
        try {
            $data['appid'] = $this->appid;
            $send = [
                'json'=>$data
            ];
            $resp = $this->instance->chain('v3/transfer/batches')->postAsync($send)->then(static function ($resp) {
                return $resp;
            })->otherwise(static function ($e) {
                if ($e instanceof RequestException && $e->hasResponse()) {
                    throw new Exception($e->getResponse()->getBody());
                }else{
                    throw new Exception($e->getMessage());
                }
            });
            $resp->wait();
            return ['code'=> $this->successCode ,'message'=>'success' ,'data'=>$responseData];

        }catch (Exception $exception){
            return ['code'=>$this->failCode,'message'=>$exception->getMessage(),'data'=>$responseData];
        }
    }

    public function queryBatchTransfer($outBatchNo,$need_query_detail=true,$offset=0,$limit=20)
    {
        if ($limit < 20){
            $limit = 20;
        }
        $responseData = [];
        try {
            $resp = $this->instance->chain('v3/transfer/batches/out-batch-no/'.$outBatchNo)->get([
                'query'=>[
                    'accept_type' => 'BATCH_TRANSFER',
                    'need_query_detail'=>$need_query_detail,
                    'offset'=>$offset,
                    'limit'=>$limit,
                    'detail_status'=>'ALL',
                ]
            ]);
            $code = $resp->getStatusCode();
            $response = $resp->getBody();
            if ($code != 200){
                throw new Exception($response);
            }
            $responseData = json_decode($response,true);
            if (json_last_error() != JSON_ERROR_NONE){
                throw new Exception('当前转账失败');
            }
            return ['code'=> $this->successCode ,'message'=>'success' ,'data'=>$responseData];

        }catch (Exception $exception){
            return ['code'=>$this->failCode,'message'=>$exception->getMessage().$exception->getLine().$exception->getFile(),'data'=>$responseData];
        }
    }
}